package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.exception.CustomException;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;


    @PostMapping
    @CacheEvict(cacheNames = "dish",key = "#dishDto.id+'_'+#dishDto.status")
    public R saveForFlavor(@RequestBody DishDto dishDto) {
        log.info("新增菜品:{}", dishDto);
        dishService.saveForFlavor(dishDto);
        return R.success("新增菜品成功");
    }


    @GetMapping("/page")
    @Cacheable(cacheNames = "dish", key = "#page+'_'+#pageSize+'_'+#name")
    public R page(Integer page, Integer pageSize, String name) {
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo, lqw);
        // 以上的基础操作只是单纯的把Dish对象和表中的数据进行查询,并没有考虑到前端页面显示的分类名称
        // 所以,要结合出分类名称后再进行数据提交返回
        // 首先创建出要提交返回的结果数据resultPage  泛型肯定时dto,因为dto的数据符合前端的要求
        IPage<DishDto> resultPage = new Page<>();
        // 从正常的dishPage中get到原始的集合数据
        List<Dish> dishList = pageInfo.getRecords();
        if (dishList == null || dishList.size() == 0) {
            return R.success(pageInfo);
        }
        // 之前因为分多次取出分类id,弊端是重复的去和数据库进行交互
        // 接下来,一次性把原有数据中的categoryId拿出来,用stream流的方法放到set中去重
        // 就可以在代码的层面上优化sql,找出所有的菜品分类名称
        //根据id集合查询所有的分类 select * from category where id in (1,2,3)
        // 最后再转map集合,key设置为id,v设置为名称
        Set<Long> set = dishList.stream().map(Dish::getCategoryId).collect(Collectors.toSet());
        List<Category> list = categoryService.listByIds(set);
        Map<Long, String> map = list.stream().collect(Collectors.toMap(Category::getId, Category::getName));

        List<DishDto> dtoList = dishList.stream().map(dish -> {
            // BeanUtils.copyProperties(原, 新);将原集合中的数据拷贝至新集合
            // 因为一次只能拷贝一个数据对象,之前使用stream流及map函数完成功能
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            // 并在每一次的拷贝后 把菜品分类的名字设置进去,可以使用map的get方法找到对应的名称
            dishDto.setCategoryName(map.get(dish.getCategoryId()));
            // 在完成一次完整的拷贝操作后,把新的数据进行返回,让流的收集方法进行收集
            return dishDto;
        }).collect(Collectors.toList());


        // 最后把集合数据和总的数据数量封装到resultPage中并返回
        resultPage.setRecords(dtoList);
        resultPage.setTotal(pageInfo.getTotal());
        return R.success(resultPage);
    }

/*    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, String name) {

        IPage<DishDto> pageInfo = dishService.getPageByName(page, pageSize, name);
        return R.success(pageInfo);
    }*/

    @PutMapping
    public R update(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);
        return R.success("修改成功");
    }

    @PostMapping("/status/{type}")
    public R updateStatus(@PathVariable Integer type, Long[] ids) {
        log.info("要修改的有{}", ids);
        dishService.updateStatus(type, ids);

        return R.success("修改成功");
    }

/*    @PostMapping("/status/1")
    public R updateStatus2(Long[] ids) {
        log.info("要修改的有{}",ids);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dish::getId,ids);
        List<Dish> list = dishService.list(lqw);
        for (Dish dish : list) {
            if (dish.getStatus() == 1){
                dish.setStatus(0);
            } else if (dish.getStatus() == 0) {
                dish.setStatus(1);
            }
            dishService.updateById(dish);
        }

        return R.success("修改成功");
    }*/

    @GetMapping("/{id}")
    public R getByIdWithFlavor(@PathVariable Long id) {
        log.info("要查询的是{}", id);
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @DeleteMapping
    @CacheEvict(cacheNames = "dish",allEntries = true)
    public R deleteByIds(Long[] ids) {

        dishService.deleteByIds(ids);
        return R.success("删除成功");
    }

    //E. 根据菜品分类ID,查询菜品列表   请求方式 GET     请求路径/dish/list  请求参数 ?categoryId=1397844263642378242
    // 在查询时，需要根据菜品分类categoryId进行查询，并且还要限定菜品的状态为起售状态(status为1)，然后对查询的结果进行排序。
    @GetMapping("/list")
    @Cacheable(cacheNames = "dish", key = "#categoryId+'_'+#name")
    public R list(Long categoryId, String name) {
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId, categoryId);
        lqw.eq(Dish::getStatus, 1);
        lqw.like(name != null, Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);

        //B. 遍历菜品列表，并查询菜品的分类信息及菜品的口味列表
        List<DishDto> dtoList = list.stream().map(dish -> {
            DishDto dishDto = new DishDto();
            //C. 组装数据DishDto，并返回
            BeanUtils.copyProperties(dish, dishDto);
            // select * from 菜品口味关联表 where dishid = dish的id
            LambdaQueryWrapper<DishFlavor> dfLqw = new LambdaQueryWrapper<>();
            dfLqw.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> flavors = dishFlavorService.list(dfLqw);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());
        // 返回整个dto的集合,数据全;
        return R.success(dtoList);
    }
}
